﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using System.Diagnostics;
using System.Drawing;

using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;

namespace ExcelAdjacencyListToDot
{
   public partial class Ribbon
   {
      private void RunBtn_Click(object sender, RibbonControlEventArgs e)
      {
         Run();
      }

      private void Run()
      {
         var app = Globals.ThisAddIn.Application;

         Excel.Worksheet thisSheet = app.ActiveSheet;
         int numBlankRows = 0;

         Excel.Workbook wb = app.ActiveWorkbook;

         var path = string.IsNullOrWhiteSpace(wb.Path) ? app.DefaultFilePath : wb.Path;

         var outFile = Path.Combine(path, Path.ChangeExtension(wb.Name, ".dot"));

         using (var writer = new StreamWriter(outFile))
         {
            writer.WriteLine("digraph g{");

            for (int r = 1; ; ++r)
            {
               var nodeLabel = ((thisSheet.Cells[r, 1] as Excel.Range).Value as string);

               if (string.IsNullOrWhiteSpace(nodeLabel))
               {
                  ++numBlankRows;
                  if (numBlankRows == 1)
                  {
                     writer.WriteLine();
                  }
                  else if (numBlankRows == 2)
                  {
                     break; // Stop after encountering 3 blank rows in a row
                  }
                  continue;
               }
               else
               {
                  numBlankRows = 0;
               }

               var startNodeName = nodeLabel.Replace(' ', '_').ToLowerInvariant();
               writer.WriteLine("{0}[label=\"{1}\"];", startNodeName, nodeLabel);

               for (int c = 2; ; ++c)
               {
                  var nodeName = ((thisSheet.Cells[r, c] as Excel.Range).Value as string);
                  if (string.IsNullOrWhiteSpace(nodeName))
                  {
                     break;
                  }

                  nodeName = nodeName.Replace(' ', '_').ToLowerInvariant();

                  writer.WriteLine("{0}->{1}", startNodeName, nodeName);
               }
               writer.WriteLine();
            }

            writer.WriteLine("}");
         }

         var imageFile = Path.ChangeExtension(outFile, ".bmp");

         Process p = new Process();
         p.StartInfo.UseShellExecute = false;
         p.StartInfo.RedirectStandardOutput = true;
         p.StartInfo.FileName = string.Format("dot");
         p.StartInfo.Arguments = string.Format("\"{0}\" -T bmp -o \"{1}\"", outFile, imageFile);
         p.Start();
         p.WaitForExit();

         Excel.Worksheet imageSheet = null;

         for(int i = 1; i <= wb.Worksheets.Count; ++i)
         {
            if (thisSheet == (Excel.Worksheet)(wb.Worksheets[i]))
            {
               if (i < wb.Worksheets.Count)
               {
                  imageSheet = wb.Worksheets[i + 1];
               }
            }
         }

         if (imageSheet == null)
         {
            imageSheet = (Excel.Worksheet)(wb.Worksheets.Add());
         }

         var image = Image.FromFile(imageFile);

         System.Windows.Forms.Clipboard.SetImage(image);
         imageSheet.Paste(imageSheet.Cells[1,1], imageFile);
      }
   }
}
